package cc.beup.common.util;

import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * @Author: Byron Bai
 * @Date: 2021/4/18 20:13
 * @Description: 对象拷贝工具类
 */
@Slf4j
public class PlatFormBeanCopyUtil {

    private PlatFormBeanCopyUtil() {
    }

    /**
     * 单个对象转换
     *
     * @param sourceObject 源对象
     * @param targetClass  目标对象
     * @return T
     * @Author: Byron Bai
     * @Date: 2021/4/18 20:13
     */
    public static <F, T> T entityToModel(F sourceObject, Class<T> targetClass) {
        T model = null;
        if (sourceObject == null || targetClass == null) {
            return null;
        }
        try {
            model = targetClass.newInstance();
        } catch (InstantiationException e) {
            log.error("entityToModel : 实例化异常", e);
        } catch (IllegalAccessException e) {
            log.error("entityToModel : 安全权限异常", e);
        }
        BeanUtils.copyProperties(sourceObject, model);
        return model;
    }

    /**
     * 批量对象转换
     *
     * @param sourceList  源List
     * @param targetClass 目标List
     * @return java.util.List<T>
     * @Author: Byron Bai
     * @Date: 2021/4/18 20:13
     */
    public static <F, T> List<T> sourceListToTargetList(List<F> sourceList, Class<T> targetClass) {
        if (sourceList == null || sourceList.size() < 1) {
            return new ArrayList<>();
        }
        List<T> tList = new ArrayList<>();
        for (F f : sourceList) {
            T t = entityToModel(f, targetClass);
            tList.add(t);
        }
        return tList;
    }

    /**
     * page类转换
     *
     * @param sourcePage  源对象
     * @param targetClass 目标对象
     * @return com.github.pagehelper.PageInfo<T>
     * @Author: xuye
     * @Date: 2021/4/18 20:13
     */
    public static <F, T> PageInfo<T> sourcePageToTargetPage(PageInfo<F> sourcePage, Class<T> targetClass) {
        PageInfo<T> pageInfo = new PageInfo<>();
        if (sourcePage == null) {
            return pageInfo;
        }
        BeanUtils.copyProperties(sourcePage, pageInfo, "list");
        if (sourcePage.getList() != null && sourcePage.getList().size() > 0) {
            List<T> targetList = sourceListToTargetList(sourcePage.getList(), targetClass);
            pageInfo.setList(targetList);
        }
        return pageInfo;
    }

}